package org.ckq.base;

import java.util.Iterator;

/**
 * Created by chenkaiqing on 17/8/17.
 */
public class Map<k,v> {
    private LinkedList<Entry<k,v>>[] linkedLists = new LinkedList[16];
    private int size;

    public void put(k key,v value){
        if(size> linkedLists.length*0.75){
            resize();
        }
        int index = 0;
        if(key != null){
            index = key.hashCode()% linkedLists.length;
        }
        Entry<k,v> entry = new Entry<>(key,value);
        int i = linkedLists[index].put(entry);
        size = size + i;
    }

    public v get(k key){
        int index = 0;
        if(key != null){
            index = key.hashCode()% linkedLists.length;
        }
        Entry<k,v> entry = new Entry<>(key,null);
        Entry<k,v> e = linkedLists[index].get(entry);
        return e.value;
    }
    public int size(){
        return size;
    }

    private void resize() {
        LinkedList<Entry<k,v>>[] newEntries = new LinkedList[linkedLists.length*2];
        Array.copy(linkedLists,newEntries);
        //reput linked list
        for(int i=0;i< linkedLists.length;i++){
            //todo iterate through linked list
            LinkedList<Entry<k,v>> linkedList = newEntries[i];
            for(Entry<k,v> e : linkedList){
            }
        }
        linkedLists = newEntries;
    }



    private class Entry<k,v>{
        private k key;
        private v value;
        public Entry(k key,v value){
            this.key = key;
            this.value = value;
        }

        @Override
        public boolean equals(Object obj) {
            if(obj instanceof Entry){
                Entry<k,v> entry = (Entry<k,v>)obj;
                if(entry.key == null && key == null){
                    return true;
                }
                if(entry.key != null && key != null && entry.key.equals(key)){
                    return true;
                }
            }
            return false;
        }
    }
}
